package com.frejoys.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.agent.AgentRoleSaveDto;
import com.frejoys.common.dto.agent.AgentRoleUpdateDto;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.agent.AgentRoleVo;
import com.frejoys.dao.entity.AgentRole;
import com.frejoys.dao.mapper.AgentRoleGroupMapper;
import com.frejoys.dao.mapper.AgentRoleMapper;
import com.frejoys.service.AgentRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@RequiredArgsConstructor
public class AgentRoleServiceImpl extends ServiceImpl<AgentRoleMapper, AgentRole> implements AgentRoleService {

    private final AgentRoleGroupMapper agentRoleGroupMapper;


    @Override
    public List<AgentRole> getList() {
        return list();
    }

    @Override
    public Map<Integer, Integer> getListById(List<AgentRole> agentRoles, List<Integer> id) {
        Map<Integer, Integer> m = new HashMap<>();

        for (AgentRole e : agentRoles) {
            if (id.contains(e.getId())) {
                Integer v = m.get(e.getId());
                if (v == null) {
                    m.put(e.getId(), e.getRebateRatio());
                }
            }
        }

        return m;
    }

    /**
     * 后台设置代理角色
     *
     * @param dto
     */
    @Override
    public boolean saveAgentRole(AgentRoleSaveDto dto) {

        if (validateARole(dto.getName(), null)) {
            //代理角色已存在
            throw new GeneralException(HttpStatus.agentRoleExist);
        }
        //查询出上级层级
        String path = baseMapper.getPidPath(dto.getPid());

        AgentRole role = new AgentRole();
        BeanUtils.copyProperties(dto, role);
        role.setCreateTime(TimeUtil.unixTime());
//        role.setPath(CommonUtil.getPath(path));
        return save(role);
    }


    /**
     * 后台修改代理角色
     *
     * @param dto
     */
    @Override
    public boolean updateAgentRole(AgentRoleUpdateDto dto) {
        if (validateARole(dto.getName(), dto.getId())) {
            //代理角色已存在
            throw new GeneralException(HttpStatus.agentRoleExist);
        }

        LambdaUpdateWrapper<AgentRole> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(AgentRole::getId, dto.getId());
        if (StrUtil.isNotEmpty(dto.getName())) {
            wrapper.set(AgentRole::getName, dto.getName());
        }
        if (ObjectUtil.isNotEmpty(dto.getRebateRatio())) {
            wrapper.set(AgentRole::getRebateRatio, dto.getRebateRatio());
        }
        return update(wrapper);
    }

    /**
     * 后台查询代理角色
     */
    @Override
    public List<AgentRoleVo> searchAgentRoleList() {
        List<AgentRoleVo> roleVos = baseMapper.listAgentRole();

        if (!roleVos.isEmpty()) {
            //先筛选出第一级
            List<AgentRoleVo> first = roleVos.stream().filter(r -> "0".equals(r.getPath())).toList();

            return setChild(first, roleVos);
        }
        return Collections.emptyList();
    }

    /**
     * 验重
     *
     * @param name
     * @param id
     */
    private boolean validateARole(String name, Integer id) {
        LambdaQueryWrapper<AgentRole> wrapper = Wrappers.lambdaQuery();
        wrapper.select(AgentRole::getId).eq(AgentRole::getName, name);
        if (ObjectUtil.isNotEmpty(id)) {
            wrapper.ne(AgentRole::getId, id);
        }
        return ObjectUtil.isNotEmpty(getOnly(wrapper));
    }


    /**
     * 递归设置下级
     *
     * @param first   第一层
     * @param roleVos 总数据
     * @return
     */
    private List<AgentRoleVo> setChild(List<AgentRoleVo> first, List<AgentRoleVo> roleVos) {
        if (CollectionUtil.isNotEmpty(first)) {
            for (AgentRoleVo roleVo : first) {
                List<AgentRoleVo> childs = roleVos.stream().filter(r -> r.getPid().equals(roleVo.getId())).toList();
                roleVo.setRoleVos(setChild(childs, roleVos));
            }
            return first;
        }
        return null;
    }
}
